﻿using System;
using System.Net;
using System.Xml.Linq;
using ForecastParser.Mobile.Model;

namespace ForecastParser.Mobile.Service
{
    public delegate void WeatherFeedDownloadCompleteHandler(object sender, WeatherDownloadCompleteEventArgs args);
    public class WeatherFeedDownloader : IWeatherFeedDownloader
    {
        public event WeatherFeedDownloadCompleteHandler DownloadComplete;
        private readonly Uri _uri;

        public WeatherFeedDownloader(string longitude, string latitude)
        {
            _uri = BuildWeatherUri(longitude, latitude);
        }

        public void DownloadForecast()
        {
            var client = new WebClient();
            client.DownloadStringCompleted += ClientDownloadStringCompleted;
            client.DownloadStringAsync(_uri);
        }

        protected virtual void OnDownloadComplete(WeatherDownloadCompleteEventArgs args)
        {
            if (DownloadComplete == null) return;
            DownloadComplete(this, args);
        }

        void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null) return;
            var forecast = GetForecast(e.Result);
            var args = new WeatherDownloadCompleteEventArgs(_uri, forecast);
            OnDownloadComplete(args);
        }

        private static Forecast GetForecast(string rawXml)
        {
            if (string.IsNullOrEmpty(rawXml)) return new Forecast();
            var root = XElement.Parse(rawXml);
            var service = new WeatherService();
            return service.GetDigitalDwmlForecast(root);
        }

        private static Uri BuildWeatherUri(string longitude, string latitude)
        {
            const string urlTemplate = "http://forecast.weather.gov/MapClick.php?lat={0}&lon={1}&FcstType=digitalDWML";
            var url = string.Format(urlTemplate, longitude, latitude);
            return new Uri(url);
        }
    }
}
